<?php
/**
 * @author kysu
 * @copyright 2011
 */

class DataProvider {
    
    protected $dbname;
    private $connection;

    /**
     * execialize
     * @param $sql
     * @return null|resource
     */
    public function exec($sql) {
        $host = null;$user = null;$pass = null;$dbname = null; //Disable warning in IDE
        include('inc/ceolink.db.inc.php');
        include_once('inc/error.inc.php');

        $this->showQuery($sql);
        try {
        // Tao ket noi CSDL
        if (!($this->connection = mysql_connect($host,$user,$pass)))
            echo "Couldn't connect to server";//die ("Couldn't connect to server");
        }
        catch(Exception $err) {
            return null;
        }

        if (!(mysql_select_db($dbname,$this->connection)))
            showError();

        // Thiet lap font Unicode
        if (!(mysql_query("set names 'utf8'")))
            showError();

        // Thuc thi cau truy van
        if (!($result = mysql_query($sql, $this->connection))){
            showError();
            return null;
        }

        return $result;
    }

    /**
     * Disconnect
     */
    private function disconnect() {
    		if (!(mysql_close($this->connection)))
    			showError();
    }

    /**
     * Use for SELECT
     * @param $sql
     * @return resource
     */
	public function executeQuery($sql) {

        $result = $this->exec($sql);

		$this->disconnect();
		
		return $result;
	}

    /**
     * Use for INSERT, UPDATE or DELETE
     * @param $sql
     * @param $para
     * @return int|resource
     */
	public function executeNonQuery($sql, $flag = 0) {

        $result = $this->exec($sql, $flag);

        if($flag == 0){
            return mysql_affected_rows();
        }
        elseif($flag == 1)
            return mysql_insert_id();

        $this->disconnect();
		
		return $result;
	}
	
	/**
     * Use for SELECT a single value.
     * @param $sql
     * @return string
     */
	public function executeScalar($sql, $field = '') {
        $result = $this->exec($sql);

        $this->disconnect();
		
		if($field != '') {
			return mysql_result($result,0, $field);
		}
		else {
			return mysql_result($result,0);
		}		
	}

    /**
     * Show query string fo debug
     * @param $sql
     */
    private function showQuery($sql) {
        //echo "<p>".$sql."</p>";
    }
}
?>